package com.example.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.library.common.Result;
import com.example.library.entity.Appointment;
import com.example.library.entity.Book;
import com.example.library.entity.Borrow;
import com.example.library.entity.User;
import com.example.library.mapper.BorrowMapper;
import com.example.library.service.IAppointmentService;
import com.example.library.service.IBookService;
import com.example.library.service.IBorrowService;
import com.example.library.service.IUserService;
import com.example.library.service.impl.UserServiceImpl;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.library.service.IBorrowService;
import com.example.library.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 胡绍杆
 * @since 2022-06-16
 */
@ResponseBody
@RestController
@RequestMapping("/borrow")
public class BorrowController {

    @Autowired
    private IBorrowService borrowService;
    @Autowired
    private IBookService iBookService;
    @Autowired
    private IAppointmentService iAppointmentService;
    @Autowired
    private IUserService iUserService;

    /**
     * yang
     * 图书借阅
     * 根据传入的account, bookNum实现用户借阅图书
     */
    @Transactional
    @GetMapping("/setBorrowInfoY")
    public Result setBorrowInfoY(@RequestParam(value = "account") String account,
                                 @RequestParam(value = "bookNum") String bookNum) {
        System.out.println(account + "," + bookNum);
        try{
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String val1 = formatter.format(date); // 当前时间
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String beforeMonthDate = simpleDateFormat.format(calendar.getTime()); // 一月前
            Calendar calendar1 = Calendar.getInstance();
            calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH) + 1);
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String beforeMonthDate1 = simpleDateFormat1.format(calendar1.getTime()); // 一月后
            // 判断是否重复借阅
            int num00 = iBorrowService.count(new QueryWrapper<Borrow>().eq("accout",account)
                    .eq("book_num",bookNum).isNull("borrow_return"));
            if(num00 == 0){
                // 是否为待取书
                Book book0 = iBookService.getOne(new QueryWrapper<Book>().eq("book_num", bookNum));

                // 判断是否有逾期未归还图书
                int num3 = iBorrowService.count(new QueryWrapper<Borrow>()
                        .eq("accout", account)
                        .between("return_time", beforeMonthDate, val1)
                        .isNull("borrow_return"));
                if (num3 == 0) {
                    // 押金是否充足
                    User user0 = iUserService.getOne(new QueryWrapper<User>()
                            .eq("account",account));
                    double cash = user0.getCash();
                    double price = book0.getPrice();
                    if(cash >= price){

                        if (book0.getBookState() == 4) { // 是否为待取
                            // 是否为本人
                            String isbn0 = book0.getIsbn();
                            int num0 = iAppointmentService.count(new QueryWrapper<Appointment>()
                                    .eq("account",account)
                                    .eq("isbn",isbn0)
                                    .eq("appointment_state",2));
                            if(num0 == 1){
                                // 修改预约记录状态
                                iAppointmentService.update(new UpdateWrapper<Appointment>()
                                        .eq("account",account)
                                        .eq("isbn",isbn0)
                                        .eq("appointment_state",2)
                                        .set("appointment_state",3));
                            } else {
                                return Result.error("100","该书已被预约"); // 该书已被预约
                            }
                        }



                        // 扣除押金
                        boolean a = iUserService.update(new UpdateWrapper<User>()
                                .eq("account",account)
                                .set("cash",cash-price));
                        // 修改图书状态
                        boolean b = iBookService.update(new UpdateWrapper<Book>()
                                .eq("book_num",bookNum)
                                .set("book_state",2));
                        // 添加借阅记录
                        Borrow borrow = new Borrow();
                        borrow.setBookNum(bookNum);
                        borrow.setAccout(account);
                        borrow.setBorrowTime(val1);
                        borrow.setReturnTime(beforeMonthDate1);
                        boolean c = iBorrowService.save(borrow);
                        if(a && b && c){
                            return Result.success(); // 借阅成功
                        } else {
                            return Result.error("101","借阅失败"); // 借阅失败
                        }
                    } else {
                        return Result.error("102","押金不足，请缴纳押金"); // 押金不足，请缴纳押金
                    }
                } else {
                    return Result.error("103","有逾期未归还图书"); // 有逾期未归还图书
                }
            } else {
                return Result.error("104","不可重复借阅");
            }
        }catch (Exception e){
            return Result.error("101","借阅失败");
        }
    }

//    当前用户正在借阅书籍
    /**
     * yang
     * 精选图书
     * 返回借阅次数最多的6本图书
     */
    @GetMapping("/getBookBorrowY")
    public Result getBookBorrowY() {
        try{
            QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("book_num,count(*) as nums").groupBy("book_num").orderByDesc("nums").last("limit 6");
            System.out.println(borrowService.list(queryWrapper));
            List<Borrow> borrows = borrowService.list(queryWrapper);
            List<String> typeList = new ArrayList<>();
            for (Borrow borrow : borrows) {
                typeList.add(borrow.getBookNum());
            }
            return Result.success(iBookService.list(new QueryWrapper<Book>().in("book_num", typeList)));
        }catch (Exception e){
            return Result.error();
        }
    }

    //    借阅记录
    @Resource
    private BorrowMapper borrowMapper;

    @ResponseBody
    @GetMapping("/borrowPage")
    public Result findByUsername(@RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize,
                                 @RequestParam String accout) {
        System.out.println(accout);
//        System.out.println(pageNum+" "+pageSize);
        QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accout", accout);
        queryWrapper.isNull("borrow_return");
//        queryWrapper.orderByDesc("return_time");
//        informService.list(new QueryWrapper<Inform>().eq("class_id",classId));
        return Result.success(borrowMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper));
    }

    //获取当前用户借阅历史
    @ResponseBody
    @GetMapping("/borrowHistory")
    public Result find(@RequestParam Integer pageNum,
                       @RequestParam Integer pageSize,
                       @RequestParam String accout
    ) {
        System.out.println(accout);
//        System.out.println(pageNum+" "+pageSize);
        QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accout", accout);
        queryWrapper.isNotNull("borrow_return");
//        queryWrapper.orderByDesc("return_time");
//        informService.list(new QueryWrapper<Inform>().eq("class_id",classId));
        return Result.success(borrowMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper));
    }
//    借阅记录中的书本信息

    @ResponseBody
    @PostMapping("/selects")
    public Result deleteBatch(@RequestBody List<String> bookNums) {
//        System.out.println(usernames);
//        usernames.toArray();
        System.out.println(bookNums);
        System.out.println("执行");
        List<Book> list = new ArrayList<>();
        for (int i = 0; i < bookNums.size(); i++) {
            QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("book_num", bookNums.get(i));
//            System.out.println(iYqUserService.getOne(queryWrapper));
            list.add(iBookService.getOne(queryWrapper));
        }
//        System.out.println(list);
//        return yqUserMapper.selectList();
        return Result.success(list);
//        return true;

    }


    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH) + 1;
    int nextMonth=calendar.get(Calendar.MONTH) + 2;
    String val1=year+"-"+month+"-1";
    String val2=year+"-"+nextMonth+"-1";

    @GetMapping("/firstChart")
    public Result firstChart(){
        QueryWrapper<Borrow> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("accout,count(*) as nums").groupBy("accout").between("borrow_time",val1,val2).orderByDesc("nums").last("limit 5");
        List<Map<String, Object>> maps = borrowService.listMaps(queryWrapper);
        return Result.success(borrowService.listMaps(queryWrapper));

    }

    @GetMapping("/secondChart")
    public Result secondChart(){
        return Result.success(borrowMapper.getForSecondChart(val1,val2));
    }

    @GetMapping("/thirdChart")
    public Result thirdChart(){
        return Result.success(borrowMapper.getForThirdChart(val1,val2));
    }

    @GetMapping("/fourthChart")
    public Result fourthChart(){
        return Result.success(borrowMapper.getForFourthChart(val1,val2));
    }

    //还书

    @Resource
    private IBorrowService iBorrowService;

    @ResponseBody
    @PostMapping("/returnBook")
    public  Result returnBook(@RequestParam String account,
                              @RequestParam Double price,
                              @RequestParam String bookNum,
                              @RequestParam String borrowReturn,
                              @RequestParam String borrowId,
                              @RequestParam String isbn){
        System.out.println(isbn);

        //返还押金
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //获取用户当前押金
        User user = iUserService.getOne(queryWrapper.eq("account", account));
        double price1 = user.getCash() + price;
        //更新用户押金
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("account", account);
        updateWrapper.set("cash", price1);
        if (!iUserService.update(updateWrapper)) {
            return Result.error();
        }
                //写入归还时间
        UpdateWrapper<Borrow> updateWrapper2=new UpdateWrapper<>();
        updateWrapper2.eq("borrow_id",borrowId);
        updateWrapper2.set("borrow_return",borrowReturn);
        if(!iBorrowService.update(updateWrapper2)){
            return Result.error();
        }
        QueryWrapper<Appointment> queryWrapper4=new QueryWrapper<>();
        queryWrapper4.eq("isbn",isbn).eq("appointment_state",1);

        if(iAppointmentService.count(queryWrapper4)==0)
        {//没有预约
            //更改书本状态
        UpdateWrapper<Book> updateWrapper1=new UpdateWrapper<>();
        updateWrapper1.eq("book_num",bookNum);
        updateWrapper1.set("book_state",1);
        if(!iBookService.update(updateWrapper1)){
            return Result.error();
        }
        }else{//有人预约
            //更改书本状态
            UpdateWrapper<Book> updateWrapper1=new UpdateWrapper<>();
            updateWrapper1.eq("book_num",bookNum);
            updateWrapper1.set("book_state",4);
            if(!iBookService.update(updateWrapper1)){
                return Result.error();
            }

            //        //更改下一位预约者状态
        List<Appointment> appointment = iAppointmentService.list(new QueryWrapper<Appointment>().eq("isbn",isbn).orderByAsc("appointment_time").last("limit 1"));
        System.out.println(appointment.get(0).getAppointmentId());
        UpdateWrapper<Appointment> updateWrapper3=new UpdateWrapper<>();
        updateWrapper3.eq("appointment_id",appointment.get(0).getAppointmentId());
        updateWrapper3.set("appointment_state",2);
        if(!iAppointmentService.update(updateWrapper3)){
            return Result.error();
        }
        }

        return Result.success();


    }

    //续借
    @SneakyThrows
    @ResponseBody
    @PostMapping("/renew")
    public Result renew(@RequestParam String borrowId,
                        @RequestParam String borrowRenew,
                        @RequestParam String accout){


        //判断当前用户有没有逾期未还的书
        //获取当前时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String val1 = formatter.format(date);
//        System.out.println(val1);
       // 获取一个月前的时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 2);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beforeMonthDate = simpleDateFormat.format(calendar.getTime());
        //统计有几条逾期记录
        int num3 = iBorrowService.count(new QueryWrapper<Borrow>()
                .eq("accout", accout).isNull("borrow_return").between("return_time", beforeMonthDate, val1));
        if(num3==0){
            //没有逾期记录
                    QueryWrapper<Borrow> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("borrow_id",borrowId);
        Borrow borrow=iBorrowService.getOne(queryWrapper);
        String start=borrow.getReturnTime();
        //把时间转成Date型
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = simpleDateFormat1.parse(val1);
        //增加一个月
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar1.add(Calendar.MONTH, 1);
        Date c1Time = calendar1.getTime();
        //把CST类型转成普通类型
        DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.US);
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String end=sdf.format(df.parse(String.valueOf(c1Time)));
        System.out.println("原时间"+start+"增加的时间"+end);

        UpdateWrapper<Borrow> updateWrapper2=new UpdateWrapper<>();
        updateWrapper2.eq("borrow_id",borrowId);
        updateWrapper2.set("borrow_renew",borrowRenew);
        updateWrapper2.set("return_time",end);
        if(iBorrowService.update(updateWrapper2)){
            return Result.success();
        }
        }else{
            return Result.error();
        }



        return Result.error();
    }

}
